package alarm.ruiqi.com.alarm_pro.options.alarm.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.ab.util.AbViewHolder;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.util.LogUtils;

import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import alarm.ruiqi.com.alarm_pro.R;
import alarm.ruiqi.com.alarm_pro.domain.AlarmEntity;
import alarm.ruiqi.com.alarm_pro.options.MainActivity;
import alarm.ruiqi.com.alarm_pro.options.alarm.AlarmInfoFragment;
import alarm.ruiqi.com.alarm_pro.service.AlarmServiceImpl;

/**
 * Created by 徐宇健 on 2015/7/6 0006.
 */
public class AlarmListAdapter extends BaseAdapter {


    //region class fields
    private Context mContext;
    private List<AlarmEntity> mData;
    private TextView mTip, mTime, mMusic , mRepeats;
    private AlarmServiceImpl service;
    private HashMap<Integer, int[]> mCheckState ; // 记录checkbox状态
    private HashSet<Integer> mSelected ;
    private  HashSet<CheckBox> checkBoxes = new HashSet<>();
    private HashSet<ToggleButton> toggleButtons = new HashSet<>();
    //endregion

    public AlarmListAdapter(Context context, List<AlarmEntity> data) {
        mContext = context;
        mData = data;
        service =new AlarmServiceImpl(context);
        LogUtils.i(" data.size() =" + data.size());

        mCheckState =  new HashMap<>();
        mSelected  = new HashSet<>();
        check();
    }



    //region other normal override methods
    @Override
    public int getCount() {

        return mData.size();
    }

    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public void notifyDataSetChanged() {
        check();
        checkBoxes.clear();
        toggleButtons.clear();
        super.notifyDataSetChanged();
    }
    //endregion

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
//        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.list_alarm_item, null);
//        }
        final AlarmEntity alarmEntity = mData.get(position);
        LogUtils.i("alarmEntity =" + alarmEntity);
        HashSet<Integer> repeat_set = alarmEntity.getHashSetRepeats();
        Calendar calendar = alarmEntity.getCalendar();
        View left = AbViewHolder.get(convertView, R.id.list_alarm_item_left_part);
        mTip = AbViewHolder.get(convertView, R.id.list_alarm_item_tip);
        mTime = AbViewHolder.get(convertView, R.id.list_alarm_item_alarm_time);
        mMusic = AbViewHolder.get(convertView, R.id.list_alarm_item_music_uri);
        ToggleButton mEnableButton;
        mEnableButton = AbViewHolder.get(convertView, R.id.list_alarm_item_toggle_enable);
        mRepeats  =  AbViewHolder.get(convertView, R.id.list_alarm_item_alarm_repeat);
        CheckBox   mCheckBox =  AbViewHolder.get(convertView, R.id.list_alarm_item_edit_checkbox);

        checkBoxes.add(mCheckBox);
        toggleButtons.add(mEnableButton);

        mTip.setText(alarmEntity.getDescription());
        mTime.setText(calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE));
        mMusic.setText(TextUtils.isEmpty(alarmEntity.getAlarmUri().toString()) ? "未设置播放音乐" : alarmEntity.getAlarmUriTitle());
        mEnableButton.setVisibility(mCheckState.get(position)[0] == CheckBox.GONE ? View.VISIBLE : View.GONE);
        mEnableButton.setChecked(alarmEntity.isEnable());
        mEnableButton.setOnCheckedChangeListener(new ToggleCheckListener(convertView, alarmEntity));
        mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (mCheckState.size()==0|| mCheckState.get(position)[0]==CheckBox.GONE) return;
                if (isChecked){
                    mCheckState.put(position, new int[]{CheckBox.VISIBLE, 1});
                    mSelected.add(mData.get(position).getId());
                }else {
                    mCheckState.put(position, new int[]{CheckBox.VISIBLE, 0});
                    mSelected.remove(mData.get(position).getId());
                }
                ((MainActivity)mContext).getHeadFragment().setHeadText(String.format("已选择%d项",mSelected.size()));
                CheckBox checkBox = (CheckBox) ((MainActivity) mContext).getHeadFragment().getmAddedRightView();
                checkBox.setChecked(mSelected.size() == mData.size()?true:false);
                LogUtils.i("设置需要删除的集合 长度 = " + mSelected);
            }
        });

        mRepeats.setText(getTex_Repeat(repeat_set));
        //更新背景
        updateLayout(convertView, alarmEntity);

        final View finalConvertView = convertView;
        left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCheckState.get(position)[0] == CheckBox.GONE) {
                    //checkbox隐藏时 为跳转事件
                    ((AlarmInfoFragment) ((MainActivity) mContext).getMainFragment()).startActionForResult(alarmEntity);
                } else {
                    //显示
                    CheckBox checkBox = (CheckBox) finalConvertView.findViewById(R.id.list_alarm_item_edit_checkbox);
                    if (checkBox.isChecked()) {
                        checkBox.setChecked(false);
                    } else {
                        checkBox.setChecked(true);
                    }
                }
            }
        });

        //=========================== 没有问题
        mCheckBox.setVisibility(mCheckState.get(position)[0]);
//        mCheckBox.setChecked(mCheckState.get(position)[1] ==0?false:true);
        mCheckBox.setChecked(mSelected.contains(alarmEntity.getId()));
        return convertView;
    }



    /**
     * 背景更新相关
     *
     * @param convertView
     * @param alarmEntity
     */
    private void updateLayout(View convertView, AlarmEntity alarmEntity) {
       ((TextView)AbViewHolder.get(convertView, R.id.list_alarm_item_tip)).setCompoundDrawablesWithIntrinsicBounds(mContext.getResources().getDrawable((alarmEntity.isEnable()) ? R.drawable.ic_alarm : R.drawable.ic_dis_alarm), null, null, null);
        convertView.findViewById(R.id.list_alarm_item_left_part).setBackgroundResource(alarmEntity.isEnable() ? R.drawable.list_alarm_item_shape : R.drawable.list_alarm_item_shape_disable);
        if (!alarmEntity.isEnable() && alarmEntity.getHashSetRepeats().size() == 0) {
            //仅一次
            convertView.findViewById(R.id.list_alarm_item_left_part).setBackgroundResource(R.drawable.list_alarm_item_shape_passed);
            ((ToggleButton)convertView.findViewById(R.id.list_alarm_item_toggle_enable)).setChecked(false);
        }
    }

    //返回重复周期的文本内容
    private String getTex_Repeat(HashSet<Integer> hashSetRepeats) {
        if(service.isOnlyOnce(hashSetRepeats)){
            return AlarmServiceImpl.ONLY_ONCE;
        }else if(service.isWorkday(hashSetRepeats)){
            return AlarmServiceImpl.WORK_DAY;
        }else if(service.isEveryDay(hashSetRepeats)){
            return AlarmServiceImpl.EVERY_DAY;
        }else {
            return service.getRepeat_s(hashSetRepeats);
        }

    }

    //检查check 状态
    private void check() {
        if (mCheckState.size()==0){
            mCheckState.put(0, new int[]{CheckBox.GONE, 0});
        }
        for(int i=0;i<mData.size();i++)
        {
            mCheckState.put(i, new int[]{mCheckState.get(0)[0] == CheckBox.GONE ? CheckBox.GONE : CheckBox.VISIBLE, 0});

        }
    }

    //region ToggleCheckListener
    class  ToggleCheckListener implements CompoundButton.OnCheckedChangeListener{

        private AlarmEntity data;
        private View convertView;
        public  ToggleCheckListener(View convertView, AlarmEntity entity){
            this.data = entity;
            this.convertView = convertView;
        }

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            LogUtils.i("alarmEntity =" + data);
            data =  service.changeEnable(data,isChecked);
            try {
                service.saveAlarm(data);
            } catch (DbException e) {
                e.printStackTrace();
                Toast.makeText(mContext,"闹钟更新失败",Toast.LENGTH_LONG).show();
                buttonView.setChecked(!isChecked);
                return;
            }
            service.createAlarm(mContext, data, isChecked);
            updateLayout(convertView, data);
            TextView v = (TextView) convertView.findViewById(R.id.list_alarm_item_tip);
            v.setText(data.getDescription());

        }
    }
    //endregion

    //region 打开修改界面 和 关闭修改界面
    //打开修改界面
    public void showEditLayout() {
        for (int i = 0; i < mData.size(); i++) {
            mCheckState.put(i, new int[]{CheckBox.VISIBLE, 0});
        }
        for (ToggleButton toggleButton : toggleButtons) {
            toggleButton.setVisibility(View.GONE);
        }
        for (CheckBox c : checkBoxes) {
            c.setVisibility(View.VISIBLE);
        }

    }
    //关闭修改界面
    public  void closeEditLayout(){
        for (ToggleButton toggleButton :toggleButtons){
            toggleButton.setVisibility(View.VISIBLE);
        }
        for (CheckBox c:checkBoxes){
            c.setChecked(false);
            c.setVisibility(View.GONE);
        }
        mSelected.clear();
        mCheckState.clear();
        check();
    }
    //endregion



    //region 设置全选 和取消全选
    public void checkAllSelect() {
        mSelected.clear();
        for (AlarmEntity e :mData){
            mSelected.add(e.getId());
        }
        for (CheckBox c:checkBoxes){
            c.setChecked(true);
        }
        LogUtils.i("全选"+mSelected.size());
    }

    //取消全选
    public void cancelAllSelect() {
        mSelected.clear();
        for (CheckBox c:checkBoxes){
            c.setChecked(false);
        }

        LogUtils.i("取消全选" + mSelected.size());
    }
    //endregion

    //region 对外公有方法
    public void setmData(List<AlarmEntity> mData) {
        this.mData = mData;
    }

    public void setCheckState(HashMap<Integer, int[]> mCheckState) {
        this.mCheckState = mCheckState;
    }

    public HashMap<Integer, int[]> getCheckState() {
        return mCheckState;
    }

    public HashSet<Integer> getSelected() {
        return mSelected;
    }
    public void clearSelect() {
        mSelected.clear();
        ((MainActivity)mContext).getHeadFragment().setHeadText(String.format("已选择%d项", mSelected.size()));
    }
    //endregion
}
